import Taro from '@tarojs/taro';

export * from './acrossApi';
export * from './is-type';
export * from './copy';
export * from './globalData';

export const getStorageData = async (key: string, isSync = true) => {
  if (isSync) {
    return Taro.getStorageSync(key);
  }
  let result: any;
  try {
    const { data } = await Taro.getStorage({ key });
    result = data;
  } catch (error) {
    console.log(error);
  }
  return result;
};

export const setStorageData = (key: string, data: any, isSync = false): Promise<TaroGeneral.CallbackResult> => {
  if (isSync) {
    return new Promise((reslove, reject) => {
      try {
        Taro.setStorageSync(key, data);
        reslove({ errMsg: 'ok' });
      } catch (e) {
        reject({ errMsg: e });
      }
    });
  }
  return Taro.setStorage({ key, data });
};
export const removeStorageData = (key: string, isSync = false): Promise<TaroGeneral.CallbackResult> => {
  if (isSync) {
    return new Promise((reslove, reject) => {
      try {
        Taro.removeStorageSync(key);
        reslove({ errMsg: 'ok' });
      } catch (e) {
        reject({ errMsg: e });
      }
    });
  }
  return Taro.removeStorage({ key });
};

// num为传入的值，n为保留的小数位
export const fomatFloat = (num: number | string, n: number): number | string => {
  let f = parseFloat(num as string);
  if (Number.isNaN(f)) {
    return num;
  }
  f = Math.round((num as number) * Math.pow(10, n)) / Math.pow(10, n); // n 幂
  return f;
};

/**
 * 补零
 * @param {*} v
 * @param {*} size
 */
function addZero(v, size) {
  for (var i = 0, len = size - (v + '').length; i < len; i++) {
    v = '0' + v;
  }
  return v + '';
}
/**
 * Parse the time to string
 * @param {(string|number)} timestamp
 * @param {string} formatStr
 * @returns {string | null}
 */
export function formatTime(timestamp: number | string, formatStr = 'yyyy-MM-dd HH:mm:ss') {
  if (!timestamp) {
    return null;
  }
  const date: any = new Date(timestamp);
  return formatStr
    .replace(/yyyy|YYYY/, date.getFullYear())
    .replace(/yy|YY/, addZero(date.getFullYear() % 100, 2))
    .replace(/-mm|-MM/, '-' + addZero(date.getMonth() + 1, 2))
    .replace(/-m|-M/g, '-' + date.getMonth() + 1)
    .replace(/dd|DD/, addZero(date.getDate(), 2))
    .replace(/d|D/g, date.getDate())
    .replace(/hh|HH/, addZero(date.getHours(), 2))
    .replace(/h|H/g, date.getHours())
    .replace(/:mm|:MM/, ':' + addZero(date.getMinutes(), 2))
    .replace(/i|I/g, date.getMinutes())
    .replace(/ss|SS/, addZero(date.getSeconds(), 2))
    .replace(/s|S/g, date.getSeconds())
    .replace(/w/g, date.getDay());
}

// 格式化播放次数
export const formatCount = (times) => {
  let formatTime: any = 0;
  times = times ? Number(times) : 0;
  switch (true) {
    case times > 100000000:
      formatTime = `${(times / 100000000).toFixed(1)}亿`;
      break;
    case times > 100000:
      formatTime = `${(times / 10000).toFixed(1)}万`;
      break;
    default:
      formatTime = times;
  }
  return formatTime;
};
